import web
import simplejson
import logging
from session import AuthBase, need_auth 
from printer import _Printer
import gcp

class PrinterCanNotAccessException(Exception):
    def __init__(self, printerid):
        self.printerid = printerid
    def __str__(self):
        return repr('can not access printer(%s)' % self.printerid)

def return_to_referer_page(default='/myprinters'):
    referer = web.ctx.env.get('HTTP_REFERER', default)
    raise web.seeother(referer)

class ePrintUtil:
    @classmethod
    def CheckPrinterPermission(cls, user, printerid):
        try:
            api = gcp.GoogleCloudPrint(user=user)
            data = api.search_printers()
            obj = simplejson.loads(data)
            if obj['success']:
                #find printerid in printer list
                for p in obj['printers']:
                    if(p['id'] == printerid):
                        return
        except:
            pass
    
        raise PrinterCanNotAccessException(printerid)

class ePrintEnable(AuthBase):
    @need_auth
    def GET(self, printerid):
        self.setSessionCookie()
        session = self.getSession()
        try:
            ePrintUtil.CheckPrinterPermission(session.user, printerid)
        except PrinterCanNotAccessException, e:
            logging.info(e.__str__())
            raise web.forbidden()
        
        _Printer.EnableEPrint(printerid, session.user)
        return_to_referer_page()

class ePrintDisable(AuthBase):
    @need_auth
    def GET(self, printerid):
        self.setSessionCookie()
        session = self.getSession()
        try:
            ePrintUtil.CheckPrinterPermission(session.user, printerid)
        except PrinterCanNotAccessException, e:
            logging.info(e.__str__())
            raise web.forbidden()
        
        _Printer.DisableEPrint(printerid, session.user)
        return_to_referer_page()

class ePrintRenew(AuthBase):
    @need_auth
    def GET(self, printerid):
        self.setSessionCookie()
        session = self.getSession()
        try:
            ePrintUtil.CheckPrinterPermission(session.user, printerid)
        except PrinterCanNotAccessException, e:
            logging.info(e.__str__())
            raise web.forbidden()
        
        _Printer.RenewPublishAddr(printerid, session.user)
        return_to_referer_page()
